package com.itheima.controller;

import com.github.pagehelper.Page;
import com.itheima.common.Code;
import com.itheima.common.PageResult;
import com.itheima.common.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description:表现层
 * @Version: V1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    /**
     * 添加用户
     * @param user
     * @return
     */
    @PostMapping
    public Result<User> save(@RequestBody User user){
        boolean b = userService.save(user);
        return new Result<User>(b? Code.OK:Code.ERROR, b?"新增成功":"新增失败");
    };

    /**
     * 修改用户
     * @param user
     * @return
     */
    @PutMapping
    public Result<User> update(@RequestBody User user){
        boolean b = userService.update(user);
        return new Result<User>(b? Code.OK:Code.ERROR, b?"修改成功":"修改失败");
    };

    /**
     * 删除用户
     * @param uuid
     * @return
     */
    @DeleteMapping
    public Result<User> delete(@PathVariable Integer uuid){
        boolean b = userService.delete(uuid);
        return new Result<User>(b? Code.OK:Code.ERROR, b?"删除成功":"删除失败");
    };
    /**
     * 查询单个用户信息
     * @param uuid
     * @return
     */
    @GetMapping("/{id}")
    public Result<User> get(@PathVariable("id") Integer uuid){
        User user = userService.get(uuid);
        return new Result<User>(user==null? Code.OK:Code.ERROR, user==null?"查询成功":"查询失败",user);
    };

    /**
     * 分页查询
     * @param page 当前页 从1开始
     * @param size  每页显示条数
     * @return
     */
    @GetMapping("/{page}/{size}")
    public Result<User> getAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        Page<User>pages = userService.getAll(page,size);
        //数据列表,总记录数,总页数
        PageResult pageResult = new PageResult<>(pages.getTotal(),pages.getPages(),pages.getResult());

        return new Result(Code.OK,"查询成功",pageResult);
    };


    /**
     * 根据用户名密码查询个人信息
     * @param userName 用户名
     * @param password 密码信息
     * @return
     */
    @PostMapping("/login")
    //注意：数据层操作不要和业务层操作的名称混淆，通常数据层仅反映与数据库间的信息交换，不体现业务逻辑
    public Result<User> login(String userName,String password){
        User user = userService.login(userName,password);
        return new Result(user==null? Code.OK:Code.ERROR, user==null?"查询成功":"查询失败",user);
    };
}
